<template>
	<div>
		<ProTable ref="proTable" title="售后单管理" :columns="columns" :requestApi="getTableList" :init-param="initParam">
			<!-- 表格 功能 按钮 -->
			<template #otherButton>
				<el-button @click="onExport" v-auth="'order:after-marketing:list:export:invoke'"> 导出 </el-button>
			</template>
			<!-- Expand -->
			<template #expand="scope">
				{{ scope.row }}
			</template>
			<!-- 表格操作 -->
			<template #operation="{ row }">
				<el-button
					type="primary"
					link
					v-auth="'order:after-marketing:refund:invoke'"
					v-if="
						row?.canceled != 1 &&
						((row.afterMarketingType == 0 && row.afterMarketingStatus == 6) || (row.afterMarketingType == 2 && row.afterMarketingStatus == 0))
					"
					@click="onRefund(row, true)"
				>
					同意退款
				</el-button>
				<el-divider
					direction="vertical"
					v-if="
						row?.canceled != 1 &&
						((row.afterMarketingType == 0 && row.afterMarketingStatus == 6) || (row.afterMarketingType == 2 && row.afterMarketingStatus == 0))
					"
					v-auth="'order:after-marketing:refund:invoke'"
				/>

				<el-button
					type="primary"
					link
					v-auth="'order:after-marketing:refund:invoke'"
					v-if="
						row?.canceled != 1 &&
						((row.afterMarketingType == 0 && row.afterMarketingStatus == 6) || (row.afterMarketingType == 2 && row.afterMarketingStatus == 0))
					"
					@click="onRefund(row, false)"
				>
					拒绝退款
				</el-button>
				<el-divider
					direction="vertical"
					v-if="
						row?.canceled != 1 &&
						((row.afterMarketingType == 0 && row.afterMarketingStatus == 6) || (row.afterMarketingType == 2 && row.afterMarketingStatus == 0))
					"
					v-auth="'order:after-marketing:refund:invoke'"
				/>

				<el-button
					type="primary"
					link
					v-auth="'order:after-marketing:agree:invoke'"
					v-if="row?.canceled != 1 && row.afterMarketingType == 0 && row.afterMarketingStatus == 0"
					@click="onRejection(row, 'return')"
				>
					已拒收同意退货
				</el-button>
				<el-divider
					direction="vertical"
					v-if="row?.canceled != 1 && row.afterMarketingType == 0 && row.afterMarketingStatus == 0"
					v-auth="'order:seller-remark:invoke'"
				/>

				<el-button
					type="primary"
					link
					v-auth="'order:after-marketing:express:invoke'"
					v-if="row?.canceled != 1 && row.afterMarketingType == 0 && row.afterMarketingStatus == 0"
					@click="onReturn(row, true)"
				>
					同意退货
				</el-button>
				<el-divider
					direction="vertical"
					v-if="row?.canceled != 1 && row.afterMarketingType == 0 && row.afterMarketingStatus == 0"
					v-auth="'order:after-marketing:express:invoke'"
				/>

				<el-button
					type="primary"
					link
					v-auth="'order:after-marketing:refuse:invoke'"
					v-if="row?.canceled != 1 && row.afterMarketingType == 0 && row.afterMarketingStatus == 0"
					@click="onReturn(row, false)"
				>
					拒绝退货
				</el-button>
				<el-divider
					direction="vertical"
					v-if="row?.canceled != 1 && row.afterMarketingType == 0 && row.afterMarketingStatus == 0"
					v-auth="'order:after-marketing:refuse:invoke'"
				/>

				<el-button
					type="primary"
					link
					v-auth="'order:after-marketing:help:invoke'"
					v-if="
						row?.canceled != 1 &&
						((row.afterMarketingType == 0 && row.afterMarketingStatus == 4) || (row.afterMarketingType == 1 && row.afterMarketingStatus == 8))
					"
					@click="onHelpReturn(row)"
				>
					协助买家退货
				</el-button>
				<el-divider
					direction="vertical"
					v-if="
						row?.canceled != 1 &&
						((row.afterMarketingType == 0 && row.afterMarketingStatus == 4) || (row.afterMarketingType == 1 && row.afterMarketingStatus == 8))
					"
					v-auth="'order:after-marketing:help:invoke'"
				/>

				<el-button
					type="primary"
					link
					v-auth="'order:after-marketing:agree:invoke'"
					v-if="row?.canceled != 1 && row.afterMarketingType == 1 && row.afterMarketingStatus == 0"
					@click="onRejection(row, 'exchange')"
				>
					已拒收同意换货
				</el-button>
				<el-divider
					direction="vertical"
					v-if="row?.canceled != 1 && row.afterMarketingType == 1 && row.afterMarketingStatus == 0"
					v-auth="'order:after-marketing:agree:invoke'"
				/>
				<!-- 申请换货，首次同意或拒绝换货 -->
				<el-button
					type="primary"
					link
					v-auth="'order:after-marketing:express:invoke'"
					v-if="row?.canceled != 1 && row?.afterMarketingType == 1 && row?.afterMarketingStatus == 0"
					@click="onReturn(row, true)"
				>
					同意换货
				</el-button>
				<el-divider
					direction="vertical"
					v-auth="'order:after-marketing:express:invoke'"
					v-if="row?.canceled != 1 && row?.afterMarketingType == 1 && row?.afterMarketingStatus == 0"
				/>

				<el-button
					type="primary"
					link
					v-auth="'order:after-marketing:refuse:invoke'"
					v-if="row?.canceled != 1 && row?.afterMarketingType == 1 && row?.afterMarketingStatus == 0"
					@click="onReturn(row, false)"
				>
					拒绝换货
				</el-button>
				<el-divider
					direction="vertical"
					v-auth="'order:after-marketing:refuse:invoke'"
					v-if="row?.canceled != 1 && row?.afterMarketingType == 1 && row?.afterMarketingStatus == 0"
				/>

				<!-- 申请换货，商品已退回，同意或拒绝换货 -->
				<el-button
					type="primary"
					link
					v-auth="'order:after-marketing:refund:invoke'"
					v-if="row?.canceled != 1 && row?.afterMarketingType == 1 && row?.afterMarketingStatus == 6"
					@click="onRefund(row, true)"
				>
					同意换货
				</el-button>
				<el-divider
					direction="vertical"
					v-if="row?.canceled != 1 && row?.afterMarketingType == 1 && row?.afterMarketingStatus == 6"
					v-auth="'order:after-marketing:refund:invoke'"
				/>

				<el-button
					type="primary"
					link
					v-auth="'order:after-marketing:refund:invoke'"
					v-if="row?.canceled != 1 && row?.afterMarketingType == 1 && row?.afterMarketingStatus == 6"
					@click="onRefund(row, false)"
				>
					拒绝换货
				</el-button>
				<el-divider
					direction="vertical"
					v-if="row?.canceled != 1 && row?.afterMarketingType == 1 && row?.afterMarketingStatus == 6"
					v-auth="'order:after-marketing:refund:invoke'"
				/>
				<!-- 申请换货，商品退回，同意换货后去操作换货发货 -->
				<el-button
					type="primary"
					link
					v-auth="'order:send:invoke'"
					v-if="row?.canceled != 1 && row.afterMarketingType == 1 && row.afterMarketingStatus == 11"
					@click="onShipments(row)"
				>
					换货发货
				</el-button>
				<el-divider
					direction="vertical"
					v-if="row?.canceled != 1 && row.afterMarketingType == 1 && row.afterMarketingStatus == 11"
					v-auth="'order:seller-remark:invoke'"
				/>

				<el-button type="primary" link v-auth="'order:details:invoke'" @click="() => $router.push(`/order/after-sale/detail/${row.orderId}`)">
					查看详情
				</el-button>
			</template>
		</ProTable>
		<Refund :visible="refundVisible" :row="refundRow" @handleClose="closeRefund"></Refund>
		<Return :visible="returnVisible" :row="returnRow" @handleClose="closeReturn"></Return>
		<HelpReturn :visible="helpReturnVisible" :row="helpReturnRow" @handleClose="closeHelpReturn"></HelpReturn>
		<Shipments :visible="shipmentsVisible" :row="shipmentsRow" @handleClose="closeShipments"></Shipments>
	</div>
</template>

<script setup lang="tsx" name="afterSale">
import { onMounted, ref, h, reactive, computed, nextTick } from 'vue';
import dayjs from 'dayjs';
import { useRouter } from 'vue-router';
import { ElMessageBox, ElMessage } from 'element-plus';
import ProTable from '../../../../components/ProTable/index.vue';
import { ProTableInstance, ColumnProps } from '../../../../components/ProTable/interface';
import { fetchAfterSaleList, fetchAfterSaleExport, fetcAgreeAfterSale } from '/@/api/order';
import { fenToYuan } from '/@/utils/commonFunction';
import { useDownload } from '/@/hooks/useDownload';
// 退款
import Refund from '/@/views/pages/fulfill/afterSale/dialog/refund.vue';
// 退货
import Return from '/@/views/pages/fulfill/afterSale/dialog/return.vue';
// 协助退货
import HelpReturn from '/@/views/pages/fulfill/afterSale/dialog/helpReturn.vue';
// 换货发货
import Shipments from '/@/views/pages/order/query/dialog/shipments.vue';

// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTable = ref<ProTableInstance>();

const router = useRouter();

const refundVisible = ref(false);
const refundRow = ref<any>('');

const returnVisible = ref(false);
const returnRow = ref<any>('');

const helpReturnVisible = ref(false);
const helpReturnRow = ref<any>('');

const shipmentsVisible = ref(false);
const shipmentsRow = ref<any>('');

// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({
	paramCode: 'orderNo',
	paramTimeType: 'replay',
});

const searchArr = [
	{
		label: '订单编号',
		value: 'orderNo',
	},
	{
		label: '售后编号',
		value: 'afterMarketingNo',
	},
];

const handleParams = (params: any) => {
	let data = {
		...params,
	};
	if (data.paramValue) {
		data[data.paramCode] = data.paramValue;
		delete data.paramValue;
		delete data.paramCode;
	}
	if (data.paramTime) {
		data.startTime = dayjs(data.paramTime[0]).format('YYYY-MM-DD');
		data.endTime = dayjs(data.paramTime[1]).format('YYYY-MM-DD');
		delete data.paramTimeType;
		delete data.paramTime;
	}

	return data;
};

// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getTableList"
const getTableList = (params: any) => {
	return fetchAfterSaleList(handleParams(params));
};

// 表格配置项
const columns: ColumnProps<any>[] = [
	{
		prop: 'paramValue',
		label: '订单搜索',
		isShow: false,
		search: {
			span: 2,
			render: (scope: any) => {
				const slot = {
					prepend: () => (
						<el-select
							v-model={scope.searchParam.paramCode}
							placeholder="Select"
							style="width: 100px"
							onChange={(value) => (scope.searchParam.paramCode = value)}
						>
							{searchArr.map((item) => (
								<el-option key={item.value} label={item.label} value={item.value} />
							))}
						</el-select>
					),
				};
				return <el-input v-model={scope.modelValue} v-slots={slot} placeholder={getPlaceholder.value} maxlength={50}></el-input>;
			},
		},
	},
	{
		prop: 'paramTime',
		label: '售后时间',
		isShow: false,
		search: {
			span: 2,
			xs: 1,
			sm: 1,
			md: 2,
			lg: 1,
			xl: 1,
			render: (scope: any) => {
				return (
					<div class="flex-center">
						<el-select
							v-model={scope.searchParam.paramTimeType}
							placeholder="Select"
							style="width: 100px"
							class="mini-gray-select flex-shrink"
							onChange={(value) => (scope.searchParam.paramTimeType = value)}
						>
							{[
								{
									label: '申请时间',
									value: 'replay',
								},
							].map((item) => (
								<el-option key={item.value} label={item.label} value={item.value} />
							))}
						</el-select>
						<el-date-picker
							v-model={scope.searchParam.paramTime}
							type="datetimerange"
							start-placeholder="开始时间"
							end-placeholder="结束时间"
							format="YYYY-MM-DD HH:mm:ss"
							date-format="YYYY-MM-DD"
							time-format="HH:mm:ss"
						/>
					</div>
				);
			},
		},
	},
	{
		prop: 'afterMarketingNo',
		label: '售后编号',
		minWidth: 240,
		render: (scope) => {
			return (
				<el-link type="primary" underline={false} onClick={() => router.push(`/order/after-sale/detail/${scope.row.orderId}`)}>
					{scope.row.afterMarketingNo}
				</el-link>
			);
		},
	},
	{
		prop: 'orderNo',
		label: '订单编号',
		minWidth: 240,
		render: (scope) => {
			return (
				<el-link type="primary" underline={false} onClick={() => router.push(`/order/query/detail/${scope.row.orderId}`)}>
					{scope.row.orderNo}
				</el-link>
			);
		},
	},
	{
		prop: 'requestTime',
		label: '申请时间',
		minWidth: 160,
	},
	{
		prop: 'orderType',
		label: '订单类型',
		minWidth: 180,
		search: { el: 'select', props: { placeholder: '选择订单类型', clearable: true, filterable: true } },
		enum: [
			{
				label: 'B2C实物订单',
				value: 0,
			},
			{
				label: 'B2C酒藏订单',
				value: 1,
			},
			{
				label: 'C2C酒藏订单',
				value: 2,
			},
			{
				label: '酒藏提货订单',
				value: 3,
			},
			{
				label: '代管费订单',
				value: 4,
			},
		],
	},
	{
		prop: 'products',
		label: '售后商品',
		minWidth: 120,
		render: (scope) => {
			return <div>{scope.row.products.map((item: any) => `${item.productName}*${item.productAmount}`).join(',')}</div>;
		},
	},
	{
		prop: 'expressStatus',
		label: '发货状态',
		minWidth: 100,
		enum: [
			{
				label: '未发货',
				value: 0,
			},
			{
				label: '已发货',
				value: 1,
			},
		],
	},
	{
		prop: 'amount',
		label: '订单金额',
		minWidth: 180,
		render: (scope) => {
			return fenToYuan(scope.row.amount);
		},
	},
	{
		prop: 'refund',
		label: '退款金额',
		minWidth: 120,
		render: (scope) => {
			return fenToYuan(scope.row.refund);
		},
	},
	{
		prop: 'afterMarketingType',
		label: '售后方式',
		minWidth: 120,
		search: { el: 'select', props: { placeholder: '选择售后方式', clearable: true, filterable: true } },
		enum: [
			{
				label: '退货退款',
				value: 0,
			},
			{
				label: '换货',
				value: 1,
			},
			{
				label: '仅退款',
				value: 2,
			},
		],
	},

	{
		prop: 'afterMarketingStatus',
		label: '售后状态',
		minWidth: 120,
		search: { el: 'select', props: { placeholder: '选择售后状态', clearable: true, filterable: true } },
		enum: [
			{
				label: '用户已申请，待商家处理',
				value: 0,
			},
			{
				label: '商家同意退款，退款成功',
				value: 1,
			},
			{
				label: '商家拒绝退款，退款关闭',
				value: 2,
			},
			{
				// label: '商家同意退款，退款成功（部分退款）',
				label: '商家同意退款，退款成功',
				value: 3,
			},
			{
				label: '商家同意退款退货申请，待买家退货',
				value: 4,
			},
			{
				label: '商家拒绝退款申请，退货关闭',
				value: 5,
			},
			{
				label: '用户已经退货，待商家处理',
				value: 6,
			},
			{
				label: '商家同意换货申请，待买家退货',
				value: 7,
			},
			{
				label: '商家拒绝换货申请，退货关闭',
				value: 8,
			},
			{
				label: '商家拒绝换货，换货关闭',
				value: 9,
			},
			{
				label: '商家同意换货，待商家发货',
				value: 10,
			},
			{
				label: '商家同意换货，已发货，等待用户收货',
				value: 11,
			},
			{
				label: '用户收货，换货完成',
				value: 12,
			},
			{
				label: '售后关闭，用户主动取消',
				value: 14,
			},
			{
				label: '售后关闭，超时自动关闭',
				value: 15,
			},
		],
	},
	{
		prop: 'afterMarketingReason',
		label: '售后原因',
		minWidth: 180,
		search: { el: 'select', props: { placeholder: '选择售后原因', clearable: true, filterable: true } },
		enum: [
			{
				label: '与商家协商一致退款',
				value: '与商家协商一致退款',
			},
			{
				label: '质量问题',
				value: '质量问题',
			},
			{
				label: '少件/漏发',
				value: '少件/漏发',
			},
			{
				label: '商家发错货',
				value: '商家发错货',
			},
			{
				label: '物流快递一直未送到',
				value: '物流快递一直未送到',
			},
			{
				label: '货物破损已拒签',
				value: '货物破损已拒签',
			},
			{
				label: '拍错/多拍/不喜欢',
				value: '拍错/多拍/不喜欢',
			},
			{
				label: '信息填写错误',
				value: '信息填写错误',
			},
			{
				label: '暂时不需要了',
				value: '暂时不需要了',
			},
			{
				label: '其他原因',
				value: '其他原因',
			},
		],
		render: (scope) => {
			return scope.row.afterMarketingReason;
		},
	},
	{ prop: 'operation', label: '操作', fixed: 'right', width: 300, align: 'left' },
];

// 保存并导出
const onExport = () => {
	ElMessageBox.confirm('确认导出数据?', '温馨提示', { type: 'warning' }).then(() =>
		useDownload(fetchAfterSaleExport, '售后单列表', handleParams(proTable.value?.searchParam))
	);
};

const getPlaceholder = computed(() => {
	const target = searchArr.find((item) => {
		return item.value == proTable.value?.searchParam.paramCode;
	});
	return target ? `输入${target?.label}搜索` : '';
});

const onRefund = (row: any, pass: any) => {
	refundRow.value = {
		...row,
		pass,
	};
	refundVisible.value = true;
};

const closeRefund = () => {
	refundVisible.value = false;
	refundRow.value = null;
	proTable.value?.getTableList();
};

const onReturn = (row: any, pass: any) => {
	returnRow.value = {
		...row,
		pass,
	};
	returnVisible.value = true;
};

const closeReturn = () => {
	returnVisible.value = false;
	returnRow.value = null;
	proTable.value?.getTableList();
};

const onHelpReturn = (row: any) => {
	helpReturnRow.value = row;
	helpReturnVisible.value = true;
};

const closeHelpReturn = () => {
	helpReturnVisible.value = false;
	helpReturnRow.value = null;
	proTable.value?.getTableList();
};

// 订单发货
const onShipments = (row: any) => {
	shipmentsVisible.value = true;
	shipmentsRow.value = row;
};

const closeShipments = (success: boolean) => {
	shipmentsVisible.value = false;
	shipmentsRow.value = null;
	if (success) {
		proTable.value?.getTableList();
	}
};

// 已拒收同意退货/换货
const onRejection = (row: any, type: any) => {
	const info: any = {
		return: '是否确认用户已拒收并同意退货?',
		exchange: '是否确认用户已拒收并同意换货?',
	};
	ElMessageBox.confirm(info[type], '温馨提示', { type: 'warning' }).then(() => {
		fetcAgreeAfterSale({
			id: row.id,
		}).then(() => {
			ElMessage.success('操作成功');
			proTable.value.getTableList();
		});
	});
};
</script>

<style lang="scss">
.demo-tabs {
	.el-tabs__header {
		margin-bottom: 0;
	}
}
</style>
